//
//  MessageViewController.m
//  Double
//
//  Created by 袁庆秋 on 15/5/21.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "MessageViewController.h"
#import "CoserDetailViewController.h"
#import "CoserCell.h"
#import "CoserModel.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "MJRefresh.h"
@interface MessageViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, assign) NSInteger i;

@end

@implementation MessageViewController

- (void)dealloc
{
    [_collectArray release];
    [_collectView release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.collectArray = [NSMutableArray array];
        self.i = 2;
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    [self startConnection];
    [self createCollectionView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"COSER";
    
    
}

#pragma mark -
#pragma mark 请求数据
- (void)startConnection
{
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=Activity&ios=23&pad=0&a=coserList&page=1&limit=16"];
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        NSArray *bigArray = [bigDic objectForKey:@"list"];
        for (NSDictionary *dic in bigArray) {
                CoserModel *model = [[CoserModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.collectArray addObject:model];
            [model release];
        }
        [self.collectView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}



#pragma mark -
#pragma mark 创建collectionView
- (void)createCollectionView
{

    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
//    flow.itemSize = CGSizeMake((self.view.frame.size.width - 40) / 2, 240);
    flow.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collectView = [[UICollectionView alloc]  initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:flow];
    [self.collectView setBackgroundColor:[UIColor whiteColor]];
    [_collectView registerClass:[CoserCell class] forCellWithReuseIdentifier:@"cell"];
    _collectView.dataSource = self;
    _collectView.delegate = self;
    [self.collectView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(viewRefresh)];
    [self.collectView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(viewLoad)];
    [self.view addSubview:_collectView];
}

#pragma mark -
#pragma mark 上拉加载
- (void)viewLoad
{
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=Activity&ios=23&pad=0&a=coserList&page=%ld&limit=16", (long)self.i];
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        NSArray *bigArray = [bigDic objectForKey:@"list"];
        if (bigArray.count == 0) {
            [self.collectView removeFooter];
            return ;
        }
        for (NSDictionary *dic in bigArray) {
            CoserModel *model = [[CoserModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.collectArray addObject:model];
            [model release];
        }
        self.i += 1;
        [self.collectView.footer endRefreshing];
        [self.collectView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.collectView.footer endRefreshing];
    }];
}

#pragma mark -
#pragma mark 下拉刷新
- (void)viewRefresh
{
    [self.collectView reloadData];
    [self.collectView.header endRefreshing];
}

#pragma mark -
#pragma mark 实现cell协议

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.collectArray.count;
}


#pragma mark -
#pragma mark 左右两列的item大小不一样
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item % 2 == 0) {
        return CGSizeMake((self.view.frame.size.width - 30) / 2, 180);
    }
    return CGSizeMake((self.view.frame.size.width - 30) / 2, 200);
}

#pragma mark -
#pragma mark 为每一个item赋值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CoserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    CoserModel *model = [self.collectArray objectAtIndex:indexPath.item];
    [cell setModel:model];
    return cell;
}

#pragma mark -
#pragma mark item点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CoserModel *model = [self.collectArray objectAtIndex:indexPath.item];
    CoserDetailViewController *detail = [[CoserDetailViewController alloc] init];
    detail.picUrl = model.myId;
    detail.desc = model.desc;
    detail.name = model.name;
    
    CATransition *trans = [CATransition animation];
    trans.type = @"push";
    trans.duration = 0.6f;
    trans.subtype = @"fromLeft";
    trans.type = @"cameraIrisHollowClose";
    [self.navigationController.view.layer addAnimation:trans forKey:nil];
    
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
